<?php

namespace Liuhelong\LaravelAdmin\Wechat\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Storage;
use Illuminate\Support\Facades\Http;

class WechatOffiaccountMpNewsArticle extends Model
{
    use DefaultDatetimeFormat;
	protected $primaryKey = 'article_id';
	public $incrementing = false;
	private $wechat;
	protected $dates = [
		'update_time'
	];
	
	public function __construct(){
		parent::__construct();
		$this->wechat = app('liuhelong_wechat_service');
	}
	
	
	public function paginate($perPage=null,$array=[])
    {
        
        $perPage = $perPage??Request::get('per_page', 10);
        $page = Request::get('page', 1);
        
        $start = ($page-1)*$perPage;
        $url = "https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token=";
        $access_token = $this->wechat->handle('access_token','getToken');
        //$data = $this->wechat->handle('material','list',[$type, $start, $perPage]);
        $data = Http::post($url.$access_token['access_token'], [
            'offset' => $start,
            'count' => $perPage,
        ])->json();
        extract($data);

		$list = static::hydrate($item);
		
		if(!empty($array)){
		    foreach($list as $k=>$v){
		        foreach($array as $n){
		            $filter = explode("as",$n);
		            if(isset($v[trim($filter[0])])){
		                $v[trim($filter[1])] = $v[trim($filter[0])];
		            }
		        }
		        $list[$k] = $v;
		    }
		}
        $paginator = new LengthAwarePaginator($list, $total_count, $perPage);

        $paginator->setPath(url()->current());

        return $paginator;
    }

    public static function with($relations)
    {
        return new static;
    }
	
	protected function findOrFail($id)
	{
		$data = [
		    $this->primaryKey=>$id
	    ];
		return static::newFromBuilder($data);
	}
	// 保存提交的form数据
	public function save(array $options = [])
	{
		$attributes = $this->getAttributes();
		//$path = Storage::disk('admin')->url(Request::file('url')->store('files','admin'));
		$path = config('filesystems.disks.admin.root').DIRECTORY_SEPARATOR.Request::file('url')->store('wechat_materials','admin');
		// save $attributes
		switch($attributes['type']){
			case('image'):
				$this->wechat->handle('material','uploadImage',[$path]);
				break;
			
			case('voice'):
				$this->wechat->handle('material','uploadVoice',[$path]);
				break;
				
			case('video'):
				$this->wechat->handle('material','uploadVideo',[$path,$attributes['title'],$attributes['description']]);
				break;
		}
		
	}
	
	public function delete()
	{
		$this->wechat->handle('material','delete',[$this->getKey()]);
		
	}
    // 覆盖`orderBy`来收集排序的字段和方向
    public function orderBy($column, $direction = 'asc')
    {

    }

    // 覆盖`where`来收集筛选的字段和条件
    public function where($column, $operator = null, $value = null, $boolean = 'and')
    {
		if($column=='type'){
            $this->type = $operator;
        }
        return $this;
    }
    public function __call($method, $parameters){
        if($method=='findOrFail'){
            return $this->$method(...$parameters);
        }
        return parent::__call($method, $parameters);
    }
}